// Keepfit/pages/identify/identify.js
const db = wx.cloud.database({
  throwOnNotFound: false
})
var util= require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tempFilePaths:'',
    name:"",
    phoneNumber:"",
    IDCardNumber:"",
    commont:"",
    checkIDCardNumber:false,
    checkPhoneNumber:false,
    isAuditor:false,
    isLoding:false
  },
  getInfomation(id){
    db.collection("Identifies").where({
      openid:id
    }).get().then(res =>{
      if(res.data.length != 0){
        let info = res.data[0]
        this.setData({
          tempFilePaths:info.photoURL,
          name:info.name,
          phoneNumber:info.phone,
          IDCardNumber:info.IDCard,
        })
      }
    })
  },
  nameInput(e){
    this.setData({
      name: e.detail.value
    })
  },


  phoneInput(e){
    console.log(util.checkPhoneNumber(e.detail.value))
    if(util.checkPhoneNumber(e.detail.value)){

      db.collection("User").where({
        phoneNumber:e.detail.value
      }).get().then(res => {
        if(res.data.length == 0){//判断是否已经被注册
          this.setData({
            phoneNumber: e.detail.value,
            checkPhoneNumber:true
          })
        }else{
          wx.showToast({
            title: "手机号已被注册",
            icon: "none"
          });
          this.setData({
            phoneNumber: "",
            checkPhoneNumber:false
          })
        }
      })
    }else{
      this.setData({
        phoneNumber: e.detail.value,
        checkPhoneNumber:false
      })
    }
  },

  idCardInput(e){
    console.log(util.checkIDCardNumber(e.detail.value))
    if(util.checkIDCardNumber(e.detail.value)){
      this.setData({
        IDCardNumber: e.detail.value,
        checkIDCardNumber:true
      })

      
    }else{
      this.setData({
        IDCardNumber: e.detail.value,
        checkIDCardNumber:false
      })
    }
  },

  chooseImage:function(){
    var that = this
    wx.chooseImage({
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
      complete: (res) => {
        this.setData({
          tempFilePaths : res.tempFilePaths
        })
      },
    })
  },

  upLoadImage(filePaths){
    //目前先上传单张图片
    //return coudImagePath
   return new Promise((resolve, reject) => {
    if(filePaths.length == 1){
      const ui = wx.getStorageSync("userInfo")
      let coudImagePath = "identify/" + ui.openid +".png"
      wx.cloud.uploadFile({
        cloudPath: coudImagePath,
        filePath: filePaths[0], // 文件路径
      }).then(res => {
        // get resource ID
        console.log(res.fileID)
        resolve(res.fileID)
      }).catch(error => {
        // handle error
        reject("查询失败")
      })
    }
   })   
  },
  previewImage:function(){
    wx.previewImage({
      urls: this.data.tempFilePaths,
    })
  },

  removeImage:function(e){
    this.setData({
      tempFilePaths: []
    })
  },
  upload(e){
    console.log(this.check())
    if(this.check()){//已经注册
      //上传照片
      this.upLoadImage(this.data.tempFilePaths).then(res =>{
        console.log(res)
        let photoURL = res
        let name = this.data.name 
        let phoneNumber = this.data.phoneNumber
        let IDCardNumber = this.data.IDCardNumber
        let openid = wx.getStorageSync("userInfo").openid
        db.collection('Identifies').where({
          openid:openid
        }).get().then(res => {
          if(res.data.length == 0){
            db.collection('Identifies').add({
              data: {
                // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id，在此处场景下用数据库自动分配的就可以了
                openid:openid,
                name: name,
                phone: phoneNumber,
                IDCard: IDCardNumber,
                photoURL:photoURL,
                status: "0",
                date:new Date()
              },
              success: function(res) {
                // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                console.log(res)
                wx.showModal({
                  title: '已收到您的申请',
                  content: '我们将在3-5天内审核完毕并主动联系您！',
                  success(res){
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                })
              }
            })
          }else{
            db.collection('Identifies').where({
              openid:openid
            }).update({
              data: {
                // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id，在此处场景下用数据库自动分配的就可以了
                name: name,
                phone: phoneNumber,
                IDCard: IDCardNumber,
                photoURL:photoURL,
                status: "0",
                date:new Date()
              },
              success: function(res) {
                // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                
                wx.showModal({
                  title: '已收到您的申请',
                  content: '我们将在3-5天内审核完毕并主动联系您！',
                  success(res){
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                })
              }
            })
          }

        })
      })

    }else{
      wx.showToast({
        title: '填写还未完成',
        icon: 'none'
        })
    }
  },

  check:function(){
    console.log(this.data.name)
    console.log(this.data.checkPhoneNumber)
    if((this.data.name != "")&&(this.data.checkPhoneNumber)&&(this.data.checkIDCardNumber)&&(this.data.tempFilePaths.length != 0)){
      return true
    }else{
      return false
    }
  },

  onClickLeft(e) {
    wx.showToast({ title: '点击返回', icon: 'none' });
    wx.navigateBack({
      delta: 1
    });

  },

  pass(e){
    if(this.check()){
      var that =this
    that.setData({
      isLoding:true
    })

    db.collection('Identifies').where({
      openid:this.data.pointUser
    }).update({
      data:{
        status:"1",
      },
      success: function (params) {
        db.collection('User').where({
          openid:that.data.pointUser
        }).update({
          data:{
            isIdenti:true,
            phoneNumber:that.data.phoneNumber
          }
        }).then(res =>{
          that.setData({
            isLoding:false
          })
          wx.navigateBack({
            delta: 1
          });
        })
      }
    })
    }else{
      wx.showToast({
        title: '验证信息有误，请于用户核实',
        icon: 'none'
        })
    }
    
  },
  refuse(e){
    this.setData({
      isRefuse:true
    })
  },
  contestInput(e){
    this.setData({
      commont:e.detail.value
    })
  },
  up(e){
    db.collection('Identifies').where({
      openid:this.data.pointUser
    }).update({
      data:{
        commont:this.data.commont,
        status:"3"
      }
    }).then(res => {
      this.setData({
        isRefuse:false
      })
      wx.navigateBack({
        delta: 1
      });
    })
  },
  back(){
    this.setData({
      isRefuse:false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.info ){
      console.log(options.info)
      this.getInfomation(options.info)
      this.setData({
        pointUser:options.info,
        isAuditor:true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})